/**
 * col_drag_sort
 */
layui.define(['YunjColsTemplet','jquery','yunj'], function (exports) {

    let YunjColsTemplet = layui.YunjColsTemplet;
    let doc = document;
    let $ = layui.jquery;

    class YunjColsTempletDragSort extends YunjColsTemplet{

        constructor(options) {
            super(options);
            this.table_sortable = null;             // 当前表格数据排序对象
            this.table_sortable_box_flag = null;    // 当前表格数据排序容器标识
        }

        async renderBefore(){
            let that=this;
            that.table_sortable_box_flag=`div[lay-id=yunj_table_${that.tableId}] .layui-table-box .layui-table-main tbody`;
            await yunj.include_js('/static/yunj/libs/Sortable/Sortable.min.js');
            return 'done'
        }

        layout(){
            let that=this;
            return `<i class="yunj-table-drag-sort-item ${that.args.icon}" data-id="{{ d.id }}" title="拖拽排序"></i>`;
        }

        defineExtraEventBind(){
            let that=this;

            $(doc).bind(`yunj_table_${that.tableId}_render_table_done`,function () {
                let sortableConfig={
                    handle: ".yunj-table-drag-sort-item",
                    animation: 150,
                    ghostClass:'yunj-table-drag-sort-item-checked',
                    onUpdate: function (evt) {
                        that.table_sort_exec();
                    },
                };
                that.table_sortable=new Sortable(doc.querySelector(that.table_sortable_box_flag),sortableConfig);
            });
        }

        // 排序执行
        table_sort_exec(){
            let that=this;
            that.table_sortable.option("disabled",true);
            let filter=Object.assign({},{event:'sort',ids:[]},that.table.request_filter({convert:false}));
            $(`${that.table_sortable_box_flag} .yunj-table-drag-sort-item`).each(function () {
                filter.ids.push($(this).data('id'));
            });
            let requestData={builder_id:that.tableId,builder_async_type:'event',filter:JSON.stringify(filter)};
            yunj.request({
                url:that.url,
                data:requestData,
                eventTitle:'数据排序',
                successCallback:function (requestArgs,responseRes) {
                    that.table_sortable.option("disabled",false);
                    that.table.render_table_handle();
                },
            });
        }

    }

    exports('col_drag_sort', YunjColsTempletDragSort);
});